package com.alpha.service.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.*;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;

import java.time.Duration;

/**
 * Redis 缓存配置
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@EnableCaching
@Configuration
@RequiredArgsConstructor
public class RedisConfiguration {
    @Value("${spring.cache.redis.cache-null-values}")
    private boolean cacheNullValues;

    @Value("${spring.cache.redis.time-to-live}")
    private Duration timeToLive;

    @Value("${spring.cache.redis.key-prefix}")
    private String keyPrefix;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(timeToLive)
                .computePrefixWith(CacheKeyPrefix.prefixed(keyPrefix))
                .serializeKeysWith(SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        if (!cacheNullValues) {
            cacheConfiguration.disableCachingNullValues();
        }
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }
}
